import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Form, Icon, Input, Button} from 'antd'
import {Redirect} from 'react-router-dom'
import {LoginWrapper} from './styled'
import {actionFunc} from './store'

// import axios from 'axios'

class Login extends Component {

    render() {
        const Item = Form.Item
        const {getFieldDecorator} = this.props.form
        if (this.props.loginStatus === true) {
            return (
                <Redirect to='/'/>
            )
        } else {
            return (
                <LoginWrapper>
                    <Form onSubmit={this.handleSubmit}>
                        <Item className='form-item'>
                            {getFieldDecorator('username', {
                                rules: [
                                    {required: true, message: 'Please input username'}
                                ]
                            })(
                                <Input prefix={<Icon type='user' style={{color: 'rgb(0,0,0,.25)'}}/>}
                                       placeholder='Please input username'/>
                            )}
                        </Item>

                        <Item className='form-item'>
                            {getFieldDecorator('password', {
                                rules: [
                                    {required: true, message: 'Please input password'}
                                ]
                            })(
                                <Input prefix={<Icon type='lock' style={{color: 'rgb(0,0,0,.25)'}}/>}
                                       placeholder='Please input password'/>
                            )}
                        </Item>
                        <Button type='primary' htmlType='submit' className='login-btn' disabled={this.props.disableButton}>Log in</Button>
                    </Form>
                </LoginWrapper>
            )
        }
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.disableButton()
                this.props.login(values)
            } else {
                console.log(999)
            }
        })
    }

}

const mapState = (state) => ({
    loginStatus: state.getIn(['login', 'loginStatus']),
    disableButton: state.getIn(['login', 'disableButton'])
})
const mapDispatch = (dispatch) => ({
    login(values) {
        dispatch(actionFunc.login(values))
    },
    disableBtn(){
        dispatch(actionFunc.disableButton())
    }
})

export default connect(mapState, mapDispatch)(Form.create()(Login))
